const { addTopic } = require("../../utils/http/api")
const { baseUrl } = require("../../utils/http/http").dev
Page({
  data: {
    inId: 0,
    studentInfo: "",
    llId: 0,
    logInfo: "",
    sxtitle: "",
    sxcontent: "",
    sximages: [],
    sxvideos: [],
    deletePath: [],
    showModalState: false,
    addState: false,
    enterprise: "",
    enterprises: [{
      dictValue: 0,
      dictLabel: "数字安全",
    }],
    userGps: "",
    conferenceInfoId: 1, // 假设有一个大会ID
    createBy: 3, // 假设有一个用户ID
    topicLocation: "", // 新增字段用于存储位置信息
    getLocation: false, // 是否获取位置信息的开关
    topicTags: ''
  },

  onLoad: function (options) {
    // 页面加载时初始化
  },

  // 获取输入标题
  getInputTitle(e) {
    this.setData({
      sxtitle: e.detail.value.trim()
    });
  },

  // 获取输入内容
  getInputContent(e) {
    if (e.detail.value.length <= 1000) {
      this.setData({
        sxcontent: e.detail.value
      });
    }
  },

  // 选择图片
  chooseImages() {
    if (this.data.sximages.length == 4) {
      wx.showToast({
        title: '最多可传4张图片',
        icon: 'none'
      });
      return;
    }
    wx.getSystemInfo({
      success: (res) => {
        if (res.platform == "windows" || res.platform == "mac") {
          wx.showToast({
            title: '禁用电脑版微信上传图片',
            icon: 'none'
          });
        } else {
          wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            sizeType: ["compressed"],
            success: (res) => {
              var size = 5 * 1024 * 1024;
              if (res.tempFiles[0].size > size) {
                wx.showToast({
                  title: '可传照片不超 5M',
                  icon: 'none'
                });
              } else {
                // 上传图片
                this.uploadImageGetPath(res.tempFiles[0]);
              }
            }
          });
        }
      }
    });
  },

  // 上传图片
  uploadImageGetPath(tempFiles) {
    wx.showLoading({
      title: '上传图片',
      mask: true
    });

    var that = this;
    const uploadUrl = baseUrl+ '/resource/oss/upload'; // 替换为实际的公共IP或域名

    wx.uploadFile({
      url: uploadUrl,
      filePath: tempFiles.tempFilePath,
      name: 'file',
      formData: {},
      success(res) {
        wx.hideLoading();
        try {
          res.data = JSON.parse(res.data);
          if (res.data.code == 200) {
            var tempImages = that.data.sximages;
            tempImages.push({ 'url': res.data.data.url });
            that.setData({
              sximages: tempImages
            });
          } else {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: "网络异常，稍后再试"
            });
          }
        } catch (e) {
          wx.showModal({
            title: '错误',
            showCancel: false,
            content: "上传失败，服务器返回数据格式不正确"
          });
        }
      },
      fail(err) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          showCancel: false,
          content: "上传失败，请检查网络连接"
        });
      }
    });
  },

  // 删除图片
  deleteImgage(event) {
    var that = this;
    var tempImages = [];
    var delImages = that.data.deletePath;
    for (var i = 0; i < that.data.sximages.length; i++) {
      if (i != event.detail.index) {
        tempImages.push(that.data.sximages[i]);
      }
    }
    delImages.push(that.data.sximages[event.detail.index].url);
    that.setData({
      sximages: tempImages,
      deletePath: delImages
    });
  },

  // 选择视频
  choosevideos() {
    if (this.data.sxvideos.length == 3) {
      wx.showToast({
        title: '最多可传3个视频',
        icon: 'none'
      });
      return;
    }
    wx.getSystemInfo({
      success: (res) => {
        if (res.platform == "windows" || res.platform == "mac") {
          wx.showToast({
            title: '禁用电脑版微信上传视频',
            icon: 'none'
          });
        } else {
          wx.chooseMedia({
            count: 1,
            mediaType: ['video'],
            sourceType: ['album', 'camera'],
            maxDuration: 60,
            sizeType: ["compressed"],
            success: (res) => {
              var size = 50 * 1024 * 1024;
              if (res.tempFiles[0].duration > 200 || res.tempFiles[0].size > size) {
                wx.showToast({
                  title: '可传视频不超60秒 或50M',
                  icon: 'none'
                });
              } else {
                // 上传视频
                this.uploadVideoGetPath(res.tempFiles[0]);
              }
            }
          });
        }
      }
    });
  },

  // 上传视频
  uploadVideoGetPath(tempFiles) {
    wx.showLoading({
      title: '上传视频',
      mask: true
    });

    var that = this;
    const uploadUrl = baseUrl + '/resource/oss/upload'; // 替换为实际的公共IP或域名

    wx.uploadFile({
      url: uploadUrl,
      filePath: tempFiles.tempFilePath,
      name: 'file',
      formData: {},
      success(res) {
        wx.hideLoading();
        try {
          res.data = JSON.parse(res.data);
          if (res.data.code == 200) {
            var tempVideos = that.data.sxvideos;
            tempVideos.push({ 'url': res.data.data.url });
            that.setData({
              sxvideos: tempVideos
            });
          } else {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: "网络异常，稍后再试"
            });
          }
        } catch (e) {
          wx.showModal({
            title: '错误',
            showCancel: false,
            content: "上传失败，服务器返回数据格式不正确"
          });
        }
      },
      fail(err) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          showCancel: false,
          content: "上传失败，请检查网络连接"
        });
      }
    });
  },

  // 删除视频
  deleteVideo(event) {
    var that = this;
    var tempVideos = [];
    var delVideos = that.data.deletePath;
    for (var i = 0; i < that.data.sxvideos.length; i++) {
      if (i != event.detail.index) {
        tempVideos.push(that.data.sxvideos[i]);
      }
    }
    delVideos.push(that.data.sxvideos[event.detail.index].url);
    that.setData({
      sxvideos: tempVideos,
      deletePath: delVideos
    });
  },

  // 打开实习单位选择框
  openEnterprises() {
    this.setData({
      showModalState: true
    });
  },

  // 确定选择实习单位
  chooseEnterprises(e) {
    var dwindex = e.currentTarget.dataset.index;
    var newenterprise = this.data.enterprises[dwindex];
    this.setData({
      enterprise: newenterprise
    });
    this.closeEnterprises();
  },

  // 关闭实习单位选择框
  closeEnterprises() {
    this.setData({
      showModalState: false
    });
  },

  // 获取用户位置
  getUserLocation(callback) {
    console.log("地理位置")
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        console.log("地理位置", res)
        const latitude = res.latitude;
        const longitude = res.longitude;
        // 调用腾讯位置服务逆地理编码API
        wx.request({
          url: `https://restapi.amap.com/v3/geocode/regeo?location=${longitude},${latitude}&key=8e7083244dd40c5e88f501428e44eeca`,
          success: (res) => {
            console.log("高德地址 address", res);
            const address = res.data.regeocode.formatted_address;
            this.setData({
              topicLocation: address
            });
            callback && callback();
          },
          fail: (err) => {
            wx.hideLoading();
            wx.showModal({
              title: '错误',
              content: '无法获取地址信息，请检查网络连接',
              showCancel: false
            });
          }
        });
      },
      fail: (error) => {
        wx.hideLoading();
        console.log("地址error",error)
        wx.showModal({
          title: '警告',
          content: '无法获取位置信息，请在设置中开启定位权限',
          confirmText: '前往设置',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting['scope.userLocation']) {
                    wx.showToast({
                      title: '定位权限已开启，请重新发布',
                      icon: 'success'
                    });
                  } else {
                    wx.showToast({
                      title: '定位权限未开启，无法获取位置信息',
                      icon: 'none'
                    });
                  }
                }
              });
            }
          }
        });
      }
    });
  },

  // 切换位置开关
  toggleLocationSwitch(e) {
    this.setData({
      getLocation: e.detail.value
    });
    console.log(e.detail.value)
    if (e.detail.value) {

      wx.authorize({
        scope: 'scope.userLocation',
      })
    }

  },

  // 发布日志信息
  postLogInfo() {
    wx.showLoading({
      title: '发布中',
      mask: true
    });
    console.log("this.data.getLocation", this.data.getLocation)
    if (this.data.getLocation) {
      this.getUserLocation(() => {
        this.doPostLogInfo();
      });
    } else {
      this.setData({
        topicLocation: ''
      }, () => {
        this.doPostLogInfo();
      });
    }
  },

  // 执行发布日志信息
  doPostLogInfo() {
    const images = this.data.sximages.map(image => image.url).join(',');
    const videos = this.data.sxvideos.map(video => video.url).join(',');

    const postData = {
      topicTitle: this.data.sxtitle,
      conferenceInfoId: this.data.conferenceInfoId,
      createBy: this.data.createBy,
      topicContent: this.data.sxcontent,
      topicLocation: this.data.topicLocation,
      topicTags: this.data.topicTags, // 假设有一个默认标签，实际可以根据需要调整
      subscriptionCount: 0,
      topicDiscussions: 0,
      topicImage: images,
      topicVideoFile: videos,
      topicStatus: 1 // 默认设置为已发布
    };

    console.log("postData", postData);
    addTopic(postData).then(res => {
      wx.hideLoading();
      console.log("添加话题",res)
      if (res.code == 200) {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        // 清空数据
        this.setData({
          sxtitle: '',
          sxcontent: '',
          sximages: [],
          sxvideos: [],
          deletePath: []
        });
        wx.switchTab({
          url: '/pages/dynamicCircle/dynamicCircle',
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '发布失败，请稍后再试',
          showCancel: false
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showModal({
        title: '错误',
        content: '网络异常，请稍后再试',
        showCancel: false
      });
    });
  }
});
